<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">
<style>
    .pace .pace-progress {
        background: #1E92FB; /*进度条颜色*/
        height: 3px;
    }
    .pace .pace-progress-inner {
         box-shadow: 0 0 10px #1E92FB, 0 0 5px     #1E92FB; /*阴影颜色*/
    }
    .pace .pace-activity {
        border-top-color: #1E92FB;    /*上边框颜色*/
        border-left-color: #1E92FB;    /*左边框颜色*/
    }
</style>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">



  <meta name="google-site-verification" content="true">

<script data-ad-client="ca-pub-3331353808689126" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>







  <meta name="baidu-site-verification" content="true">







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="框架,mybatis,plugin,">





  <link rel="alternate" href="/atom.xml" title="爱吃jelly的Jelly" type="application/atom+xml">






<meta name="description" content="mybatis-plus入坑指南简介 MyBatis-Plus（简称 MP）是一个 MyBatis 的增强工具，在 MyBatis 的基础上只做增强不做改变，为简化开发、提高效率而生。">
<meta name="keywords" content="框架,mybatis,plugin">
<meta property="og:type" content="article">
<meta property="og:title" content="mybatis-plus入坑指南">
<meta property="og:url" content="https://jelly54.github.io/mybatis-plusStart/index.html">
<meta property="og:site_name" content="爱吃jelly的Jelly">
<meta property="og:description" content="mybatis-plus入坑指南简介 MyBatis-Plus（简称 MP）是一个 MyBatis 的增强工具，在 MyBatis 的基础上只做增强不做改变，为简化开发、提高效率而生。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://mp.baomidou.com/img/mybatis-plus-framework.jpg">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2019041014201985.png">
<meta property="og:updated_time" content="2020-03-07T03:47:15.829Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="mybatis-plus入坑指南">
<meta name="twitter:description" content="mybatis-plus入坑指南简介 MyBatis-Plus（简称 MP）是一个 MyBatis 的增强工具，在 MyBatis 的基础上只做增强不做改变，为简化开发、提高效率而生。">
<meta name="twitter:image" content="https://mp.baomidou.com/img/mybatis-plus-framework.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://jelly54.github.io/mybatis-plusStart/">






  <meta name="baidu-site-verification" content="t21ZdXzSqf">



<meta name="google-site-verification" content="VmrkZiYJtPrIIH8zlY82aG2_l1Ykrp3JZ3HQbMt0qCo">

  <title>mybatis-plus入坑指南 | 爱吃jelly的Jelly</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    
    <a href="https://github.com/jelly54" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">爱吃jelly的Jelly</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">就揪啾  就是 Jelly</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于作者
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://jelly54.github.io/mybatis-plusStart/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Big Jelly">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="爱吃jelly的Jelly">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">mybatis-plus入坑指南</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-03-02T16:12:33+08:00">
                2019-03-02
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/MyBatis/" itemprop="url" rel="index">
                    <span itemprop="name">MyBatis</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  4.2k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  17
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="mybatis-plus入坑指南"><a href="#mybatis-plus入坑指南" class="headerlink" title="mybatis-plus入坑指南"></a>mybatis-plus入坑指南</h1><h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><blockquote>
<p>MyBatis-Plus（简称 MP）是一个 MyBatis 的增强工具，在 MyBatis 的基础上只做增强不做改变，为简化开发、提高效率而生。</p>
</blockquote>
<a id="more"></a>

<h2 id="特性"><a href="#特性" class="headerlink" title="特性"></a>特性</h2><ul>
<li>无侵入：只做增强不做改变，引入它不会对现有工程产生影响，如丝般顺滑</li>
<li>损耗小：启动即会自动注入基本 CURD，性能基本无损耗，直接面向对象操作</li>
<li>强大的 CRUD 操作：内置通用 Mapper、通用 Service，仅仅通过少量配置即可实现单表大部分 CRUD 操作，更有强大的条件构造器，满足各类使用需求</li>
<li>支持 Lambda 形式调用：通过 Lambda 表达式，方便的编写各类查询条件，无需再担心字段写错</li>
<li>支持多种数据库：支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer2005、SQLServer 等多种数据库</li>
<li>支持主键自动生成：支持多达 4 种主键策略（内含分布式唯一 ID 生成器 - Sequence），可自由配置，完美解决主键问题</li>
<li>支持 XML 热加载：Mapper 对应的 XML 支持热加载，对于简单的 CRUD 操作，甚至可以无 XML 启动</li>
<li>支持 ActiveRecord 模式：支持 ActiveRecord 形式调用，实体类只需继承 Model 类即可进行强大的 CRUD 操作</li>
<li>支持自定义全局通用操作：支持全局通用方法注入（ Write once, use anywhere ）</li>
<li>支持关键词自动转义：支持数据库关键词（order、key……）自动转义，还可自定义关键词</li>
<li>内置代码生成器：采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码，支持模板引擎，更有超多自定义配置等您来使用</li>
<li>内置分页插件：基于 MyBatis 物理分页，开发者无需关心具体操作，配置好插件之后，写分页等同于普通 List 查询</li>
<li>内置性能分析插件：可输出 Sql 语句以及其执行时间，建议开发测试时启用该功能，能快速揪出慢查询</li>
<li>内置全局拦截插件：提供全表 delete 、 update 操作智能分析阻断，也可自定义拦截规则，预防误操作</li>
<li>内置 Sql 注入剥离器：支持 Sql 注入剥离，有效预防 Sql 注入攻击</li>
</ul>
<h2 id="框架结构"><a href="#框架结构" class="headerlink" title="框架结构"></a>框架结构</h2><p><img src="https://mp.baomidou.com/img/mybatis-plus-framework.jpg" alt="框架结构"></p>
<h2 id="好了官网的简介完了，附上github地址：Mybatis-plus的GIthub"><a href="#好了官网的简介完了，附上github地址：Mybatis-plus的GIthub" class="headerlink" title="好了官网的简介完了，附上github地址：Mybatis-plus的GIthub"></a>好了官网的简介完了，附上github地址：Mybatis-plus的GIthub</h2><h1 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h1><blockquote>
<p>代码生成器，又被叫做逆向工程，MyBatis官方为了推广，自己也写了一个，我之前也使用这个，功能也是非常强大，强大以为支持自定义配置，那么问题来了，我该怎么配置才合理呢，所以，有人把所有的配置项都弄成中文的，还有人开发了生成插件，这些在我以往的博文中都看看到。MyBatis-Plus的代码生成器到底怎么样，这我就不评判了，我就这样说，用用看吧。</p>
</blockquote>
<p>在MyBatis-Plus的官网文档中，有将代码生成器的问题，有配置详解，也有项目示例代码，复制来就可用。</p>
<h2 id="功能列表："><a href="#功能列表：" class="headerlink" title="功能列表："></a>功能列表：</h2><ul>
<li><input checked disabled type="checkbox"> <p>自动生成model类</p>
</li>
<li><input checked disabled type="checkbox"> <p>自动生成dao接口</p>
</li>
<li><input checked disabled type="checkbox"> <p>自动生成xml文件</p>
</li>
<li><input checked disabled type="checkbox"> <p>自动生成service接口</p>
</li>
<li><input checked disabled type="checkbox"> <p>自动生成service实现类</p>
</li>
<li><input checked disabled type="checkbox"> <p>model支持Builder模式</p>
</li>
<li><input checked disabled type="checkbox"> <p>支持swagger2</p>
</li>
<li><input checked disabled type="checkbox"> <p>支持生成数据库字段常量</p>
</li>
<li><input checked disabled type="checkbox"> <p>支持生成Kotlin代码</p>
</li>
<li><p>[] ……</p>
</li>
</ul>
<h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><h3 id="添加依赖"><a href="#添加依赖" class="headerlink" title="添加依赖"></a>添加依赖</h3><p>无论SSM项目还是SpringBoot项目，在原来基础上添加以下依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.projectlombok<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>lombok<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">optional</span>&gt;</span>true<span class="tag">&lt;/<span class="name">optional</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.baomidou<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-plus-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.1.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="添加包扫描"><a href="#添加包扫描" class="headerlink" title="添加包扫描"></a>添加包扫描</h3><p><strong>springboot项目</strong>  </p>
<p>在启动类上使用注解扫描mapper包（dao层）(Spring Boot项目)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@MapperScan</span>(<span class="string">"com.xxx.xxxx.mapper"</span>)</span><br></pre></td></tr></table></figure>

<p><strong>springMvc项目</strong></p>
<ul>
<li>配置 MapperScan</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.mybatis.spring.mapper.MapperScannerConfigurer"</span>&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"basePackage"</span> <span class="attr">value</span>=<span class="string">"com.baomidou.mybatisplus.samples.quickstart.mapper"</span>/&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>调整 SqlSessionFactory 为 MyBatis-Plus 的 SqlSessionFactory  </li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"sqlSessionFactory"</span> <span class="attr">class</span>=<span class="string">"com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"dataSource"</span> <span class="attr">ref</span>=<span class="string">"dataSource"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="警告"><a href="#警告" class="headerlink" title="警告"></a>警告</h3><p><strong>WARNING</strong></p>
<p>引入 MyBatis-Plus 之后请不要再次引入 MyBatis 以及 MyBatis-Spring，以避免因版本差异导致的问题。</p>
<hr>
<h1 id="Mybatis-plus的配置"><a href="#Mybatis-plus的配置" class="headerlink" title="Mybatis-plus的配置"></a>Mybatis-plus的配置</h1><h2 id="在application-yml中添加数据源"><a href="#在application-yml中添加数据源" class="headerlink" title="在application.yml中添加数据源"></a>在application.yml中添加数据源</h2><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># DataSource Config</span></span><br><span class="line"><span class="attr">spring:</span></span><br><span class="line"><span class="attr">  datasource:</span></span><br><span class="line"><span class="attr">    driver-class-name:</span> <span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">    url:</span> <span class="attr">jdbc:mysql://localhost:3306/test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8&amp;characterSetResults=utf8</span></span><br><span class="line"><span class="attr">    username:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">    password:</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># Logger Config</span></span><br><span class="line"><span class="attr">logging:</span></span><br><span class="line"><span class="attr">  level:</span></span><br><span class="line">    <span class="string">com.mybatisplus.demo03:</span> <span class="string">debug</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#MP所支持的application.yml设置 具体参考官方文档https://jobob.gitee.io/mp3doc/中设置部分</span></span><br><span class="line"><span class="attr">mybatis-plus:</span></span><br><span class="line"><span class="comment">#  config-location: classpath:mybatis/mybatis-config.xml #如果需要使用原生mybatis设置文件，则这里需要指明具体路径</span></span><br><span class="line"><span class="comment">#  mapper-locations: classpath:/mybatis/mapper/*DAO.xml #在resource目录下的写法</span></span><br><span class="line"><span class="comment">#  mapper-locations: classpath:/com/mpspringboot/mapper/xml/*Mapper.xml #在src/main/java下的写法(同时配置POM文件中source属性)</span></span><br><span class="line"><span class="comment">#  mapper-locations: classpath*:/mybatis/mapper/*DAO.xml #Maven多项目模块下使用classpath*写法</span></span><br><span class="line"><span class="comment">#  type-aliases-package: com.XX.entity #设置类名别名扫描位置，设置后可使用类名替代全限定类名，多个package用逗号或者分号分隔</span></span><br><span class="line"><span class="comment">#  type-aliases-super-type: java.lang.Object #请和typeAliasesPackage一起使用，设置后仅会扫描路径下以该类作为父类的域对象 。</span></span><br><span class="line"><span class="comment">#  type-handlers-package: com.XX.handler #设置类型转换类所在的包位置</span></span><br><span class="line"><span class="comment">#  type-enums-package: com.XX.enums #枚举字段扫描，支持实体的枚举字段</span></span><br><span class="line"><span class="comment">#  check-config-location: false #启动时是否检查 MyBatis XML 文件的存在，默认不检查。</span></span><br><span class="line"><span class="comment">#  executor-type: simple #通过该属性可指定 MyBatis 的执行器，默认值为SIMPLE，MyBatis 的执行器总共有三种：</span></span><br><span class="line"><span class="comment">#                         ExecutorType.SIMPLE：该执行器类型不做特殊的事情，为每个语句的执行创建一个新的预处理语句（PreparedStatement）</span></span><br><span class="line"><span class="comment">#                         ExecutorType.REUSE：该执行器类型会复用预处理语句（PreparedStatement）</span></span><br><span class="line"><span class="comment">#                         ExecutorType.BATCH：该执行器类型会批量执行所有的更新语句</span></span><br><span class="line"><span class="comment">#  configuration-properties: classpath:mybatis/config.properties #指定外部化 MyBatis Properties 配置，通过该配置可以抽离配置，实现不同环境的配置部署。</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">#MyBatis-Plus 全局策略配置</span></span><br><span class="line"><span class="attr">  global-config:</span></span><br><span class="line"><span class="attr">    refresh:</span> <span class="literal">true</span> <span class="comment">#启动后，修改Target中的XML即可更新对应Mapper的逻辑，用于调试；生产中不要启动</span></span><br><span class="line"><span class="comment">#    sql-parser-cache: true #是否缓存 Sql 解析，默认不缓存。</span></span><br><span class="line"><span class="comment">#    sql-session: com.xxx.SqlSession #单例重用 SqlSession</span></span><br><span class="line"><span class="comment">#    sql-session-factory: com.xxx.SqlSessionFactory #</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#全局配置中关于DB的设置</span></span><br><span class="line"><span class="attr">    db-config:</span></span><br><span class="line"><span class="attr">      db-type:</span> <span class="string">MYSQL</span> <span class="comment">#数据库类型</span></span><br><span class="line"><span class="attr">      capital-mode:</span> <span class="literal">true</span> <span class="comment">#是否开启大写命名，开启后生成SQL语句都为大写；默认不开启。</span></span><br><span class="line"><span class="comment">#      table-prefix: sys #生成的SQL会在表名上增加此前缀</span></span><br><span class="line"><span class="attr">      table-underline:</span> <span class="literal">true</span> <span class="comment">#生成的SQL语句中，表名是否自动加入驼峰转下划线（如SystemUser=&gt;system_user）</span></span><br><span class="line"><span class="attr">      field-strategy:</span> <span class="string">NOT_NULL</span> <span class="comment">#字段更新插入策略  0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"</span></span><br><span class="line"><span class="comment">#                               IGNORED：所有字段都更新和插入</span></span><br><span class="line"><span class="comment">#                               NOT_NULL：只更新和插入非NULL值</span></span><br><span class="line"><span class="comment">#                               NOT_EMPTY：只更新和插入非NULL值且非空字符串</span></span><br><span class="line"><span class="comment">#                               DEFAULT：默认NOT_NULL</span></span><br><span class="line"><span class="attr">      id-type:</span> <span class="string">UUID</span> <span class="comment">#主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";</span></span><br><span class="line"><span class="comment">#                               AUTO(0)：MP自动决定</span></span><br><span class="line"><span class="comment">#                               NONE(1)：生成语句插入null，需要数据库自增时可以使用</span></span><br><span class="line"><span class="comment">#                               INPUT(2)：根据用户输入值</span></span><br><span class="line"><span class="comment">#                               ID_WORKER(3)：全局唯一ID (数字类型唯一ID)</span></span><br><span class="line"><span class="comment">#                               UUID(4)：全局唯一ID UUID</span></span><br><span class="line"><span class="comment">#                               ID_WORKER_STR(5)：全局唯一ID (字符型类型唯一ID)</span></span><br><span class="line"><span class="attr">      column-like:</span> <span class="literal">false</span> <span class="comment">#逻辑删除字段表示未删除的值</span></span><br><span class="line"><span class="attr">      logic-delete-value:</span> <span class="number">1</span> <span class="comment">#逻辑删除字段表示删除的值</span></span><br><span class="line"><span class="attr">      logic-not-delete-value:</span> <span class="number">0</span> <span class="comment">#逻辑删除字段表示未删除的值</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  <span class="comment">#一部分对原生MyBatis所支持的配置，我建议使用config-location加mybatis-config.xml实现比较清晰，不要在这里使用</span></span><br><span class="line"><span class="comment">#  configuration:</span></span><br><span class="line"><span class="comment">#    mapUnderscoreToCamelCase: true #默认true，是否开启自动驼峰命名规则（camel case）映射，即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。</span></span><br><span class="line"><span class="comment">#    aggressive-lazy-loading: true #当设置为 true 的时候，懒加载的对象可能被任何懒属性全部加载，否则，每个属性都按需加载。需要和 lazyLoadingEnabled 一起使用。</span></span><br><span class="line"><span class="comment">#    auto-mapping-unknown-column-behavior: none #MyBatis 自动映射策略，通过该配置可指定 MyBatis 是否并且如何来自动映射数据表字段与对象的属性，总共有 3 种可选值：</span></span><br><span class="line"><span class="comment">#                                               AutoMappingBehavior.NONE：不启用自动映射</span></span><br><span class="line"><span class="comment">#                                               AutoMappingBehavior.PARTIAL：只对非嵌套的 resultMap 进行自动映射</span></span><br><span class="line"><span class="comment">#                                               AutoMappingBehavior.FULL：对所有的 resultMap 都进行自动映射</span></span><br><span class="line"><span class="comment">#    auto-mapping-behavior: partial #MyBatis 自动映射时未知列或未知属性处理策略，通过该配置可指定 MyBatis 在自动映射过程中遇到未知列或者未知属性时如何处理，总共有 3 种可选值：</span></span><br><span class="line"><span class="comment">#                                  AutoMappingUnknownColumnBehavior.NONE：不做任何处理 (默认值)</span></span><br><span class="line"><span class="comment">#                                  AutoMappingUnknownColumnBehavior.WARNING：以日志的形式打印相关警告信息</span></span><br><span class="line"><span class="comment">#                                  AutoMappingUnknownColumnBehavior.FAILING：当作映射失败处理，并抛出异常和详细信息</span></span><br><span class="line"><span class="comment">#    cache-enabled: true #全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存，默认为 true。</span></span><br><span class="line"><span class="comment">#    call-setters-on-nulls: false #指定当结果集中值为 null 的时候是否调用映射对象的 Setter（Map 对象时为 put）方法，通常运用于有 Map.keySet() 依赖或 null 值初始化的情况。</span></span><br><span class="line"><span class="comment">#                                  通俗的讲，即 MyBatis 在使用 resultMap 来映射查询结果中的列，如果查询结果中包含空值的列，则 MyBatis 在映射的时候，不会映射这个字段，这就导致在调用到该字段的时候由于没有映射，取不到而报空指针异常。</span></span><br><span class="line"><span class="comment">#                                  当您遇到类似的情况，请针对该属性进行相关配置以解决以上问题。</span></span><br><span class="line"><span class="comment">#                                  WARNING</span></span><br><span class="line"><span class="comment">#                                  基本类型（int、boolean 等）是不能设置成 null 的。</span></span><br><span class="line"><span class="comment">#    configuration-factory: com.xxx.SampleConfigurationFactory #指定一个提供 Configuration 实例的工厂类。</span></span><br><span class="line">                                    <span class="comment">#该工厂生产的实例将用来加载已经被反序列化对象的懒加载属性值，其必须包含一个签名方法static Configuration getConfiguration()。（从 3.2.3 版本开始）</span></span><br></pre></td></tr></table></figure>

<p>或者</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">mybatis-plus:</span></span><br><span class="line">  <span class="comment"># xml</span></span><br><span class="line"><span class="attr">  mapper-locations:</span> <span class="attr">classpath:mapper/*Mapper.xml</span></span><br><span class="line">  <span class="comment"># 实体扫描，多个package用逗号或者分号分隔</span></span><br><span class="line"><span class="attr">  type-aliases-package:</span> <span class="string">com.fengwenyi.mp3demo.model</span></span><br><span class="line"><span class="attr">  configuration:</span></span><br><span class="line">    <span class="comment"># 这个配置会将执行的sql打印出来，在开发或测试的时候可以用</span></span><br><span class="line"><span class="attr">    log-impl:</span> <span class="string">org.apache.ibatis.logging.stdout.StdOutImpl</span></span><br></pre></td></tr></table></figure>

<p>将sql打印在控制台中<br><img src="https://img-blog.csdnimg.cn/2019041014201985.png" alt="示例"></p>
<hr>
<h1 id="核心功能"><a href="#核心功能" class="headerlink" title="核心功能"></a>核心功能</h1><h2 id="代码生成器"><a href="#代码生成器" class="headerlink" title="代码生成器"></a>代码生成器</h2><p><strong>① 添加依赖</strong> </p>
<p>AutoGenerator 是 MyBatis-Plus 的代码生成器，通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码，极大的提升了开发效率。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.baomidou<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-plus-generator<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">version</span>&gt;</span>最新版本<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- freemarker 模板引擎 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.freemarker<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>freemarker<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>最新版本<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>② Generator类</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MysqlGenerator</span> </span>&#123;</span><br><span class="line">    <span class="comment">//要生成的表，及输出路径</span></span><br><span class="line">    <span class="keyword">static</span> String[] TO_CREATE_TABLES = <span class="keyword">new</span> String[]&#123;<span class="string">"block"</span>, <span class="string">"channel_origin"</span>, <span class="string">"channel_target"</span>, <span class="string">"order"</span>, <span class="string">"tenant"</span>, <span class="string">"user"</span>, <span class="string">"oauth_user"</span>, <span class="string">"oauth_session_key"</span>&#125;;</span><br><span class="line">    <span class="keyword">static</span> String BASE_OUT_PUT_DIR = <span class="string">"src/main/java"</span>;</span><br><span class="line">    <span class="keyword">static</span> String XML_OUT_PUT_DIR = <span class="string">"src/main/resources/mapper"</span>;</span><br><span class="line">    <span class="keyword">static</span> String AUTHOR = <span class="string">"Jelly"</span>;</span><br><span class="line">    <span class="comment">//配置数据源</span></span><br><span class="line">    <span class="keyword">static</span> String DATA_SOURCE_URL = <span class="string">"jdbc:mysql://localhost:3306/qingteng?useUnicode=true&amp;useSSL=false&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8"</span>;</span><br><span class="line">    <span class="keyword">static</span> String DATA_SOURCE_DRIVER = <span class="string">"com.mysql.cj.jdbc.Driver"</span>;</span><br><span class="line">    <span class="keyword">static</span> String DATA_SOURCE_USER = <span class="string">"root"</span>;</span><br><span class="line">    <span class="keyword">static</span> String DATA_SOURCE_PASSWORD = <span class="string">"123456"</span>;</span><br><span class="line">    <span class="comment">//生成表的父类</span></span><br><span class="line">    <span class="keyword">static</span> String SUPER_CONTROLLER = <span class="string">"com.qingtengcloud.web.v1.base.BaseController"</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 代码生成器</span></span><br><span class="line"><span class="comment">         *</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        AutoGenerator mpg = <span class="keyword">new</span> AutoGenerator();</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 包配置</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        PackageConfig pc = <span class="keyword">new</span> PackageConfig();</span><br><span class="line">        pc.setParent(<span class="string">"com.qingtengcloud"</span>); <span class="comment">//父包名。如果为空，将下面子包名必须写全部， 否则就只需写子包名</span></span><br><span class="line">        pc.setEntity(<span class="string">"bean"</span>);</span><br><span class="line">        pc.setController(<span class="string">"web.v1"</span>);</span><br><span class="line">        pc.setMapper(<span class="string">"dao"</span>);</span><br><span class="line">        pc.setXml(<span class="string">"mapper"</span>);</span><br><span class="line">        mpg.setPackageInfo(pc);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 全局配置</span></span><br><span class="line"><span class="comment">         *</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        GlobalConfig gc = <span class="keyword">new</span> GlobalConfig();</span><br><span class="line">        String projectPath = System.getProperty(<span class="string">"user.dir"</span>);</span><br><span class="line">        gc.setOpen(<span class="keyword">false</span>);<span class="comment">//        否打开输出目录</span></span><br><span class="line">        gc.setOutputDir(BASE_OUT_PUT_DIR); <span class="comment">//生成文件的输出目录</span></span><br><span class="line">        gc.setFileOverride(<span class="keyword">false</span>);<span class="comment">// 是否覆盖文件</span></span><br><span class="line">        gc.setActiveRecord(<span class="keyword">true</span>); <span class="comment">//开启 activeRecord</span></span><br><span class="line">        gc.setEnableCache(<span class="keyword">false</span>);<span class="comment">// xml 二级缓存</span></span><br><span class="line">        gc.setBaseResultMap(<span class="keyword">true</span>); <span class="comment">//xml resultMap</span></span><br><span class="line">        gc.setBaseColumnList(<span class="keyword">true</span>);<span class="comment">//xml columList</span></span><br><span class="line">        gc.setDateType(DateType.SQL_PACK);</span><br><span class="line">        gc.setAuthor(AUTHOR);</span><br><span class="line">        gc.setXmlName(<span class="string">"%sMapper"</span>);<span class="comment">//Mapper xml 命名方式</span></span><br><span class="line">        gc.setMapperName(<span class="string">"%sMapper"</span>);<span class="comment">//mapper 命名方式</span></span><br><span class="line">        gc.setServiceName(<span class="string">"%sService"</span>);<span class="comment">//service 命名方式</span></span><br><span class="line">        gc.setServiceImplName(<span class="string">"%sServiceImpl"</span>);<span class="comment">//service impl 命名方式</span></span><br><span class="line">        gc.setControllerName(<span class="string">"%sController"</span>);<span class="comment">//controller 命名方式</span></span><br><span class="line">        mpg.setGlobalConfig(gc);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 数据源配置</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        DataSourceConfig dsc = <span class="keyword">new</span> DataSourceConfig();</span><br><span class="line">        dsc.setUrl(DATA_SOURCE_URL);</span><br><span class="line">        <span class="comment">// dsc.setSchemaName("public");</span></span><br><span class="line">        dsc.setDriverName(DATA_SOURCE_DRIVER);</span><br><span class="line">        dsc.setUsername(DATA_SOURCE_USER);</span><br><span class="line">        dsc.setPassword(DATA_SOURCE_PASSWORD);</span><br><span class="line">        mpg.setDataSource(dsc);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         *  自定义配置</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        InjectionConfig cfg = <span class="keyword">new</span> InjectionConfig() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">initMap</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                <span class="comment">// to do nothing</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        List&lt;FileOutConfig&gt; focList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        focList.add(<span class="keyword">new</span> FileOutConfig(<span class="string">"templates/mapper.xml.ftl"</span>) &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> String <span class="title">outputFile</span><span class="params">(TableInfo tableInfo)</span> </span>&#123;</span><br><span class="line">                <span class="comment">// 自定义输入文件名称</span></span><br><span class="line">                <span class="keyword">return</span> XML_OUT_PUT_DIR + <span class="string">"/"</span> + tableInfo.getEntityName() + <span class="string">"Mapper"</span> + StringPool.DOT_XML;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        cfg.setFileOutConfigList(focList);</span><br><span class="line">        mpg.setCfg(cfg);</span><br><span class="line">        mpg.setTemplate(<span class="keyword">new</span> TemplateConfig().setXml(<span class="keyword">null</span>));</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 策略配置</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        StrategyConfig strategy = <span class="keyword">new</span> StrategyConfig();</span><br><span class="line">        strategy.setNaming(NamingStrategy.underline_to_camel); <span class="comment">//数据库表名映射策略，下划线转驼峰命名</span></span><br><span class="line">        strategy.setColumnNaming(NamingStrategy.underline_to_camel); <span class="comment">//数据库表字段映射到实体的命名策略，下划线转驼峰命名</span></span><br><span class="line">        strategy.setInclude(TO_CREATE_TABLES);<span class="comment">//需要包含的表名，允许正则表达式（与exclude二选一配置）</span></span><br><span class="line"><span class="comment">//        strategy.setExclude(new String[]&#123;"test"&#125;); // 排除生成的表</span></span><br><span class="line">        strategy.setEntityBuilderModel(<span class="keyword">true</span>);<span class="comment">//是否为构建者模型</span></span><br><span class="line">        strategy.setEntityLombokModel(<span class="keyword">true</span>); <span class="comment">//是否为lombok模型</span></span><br><span class="line">        strategy.setSuperControllerClass(SUPER_CONTROLLER);<span class="comment">//自定义继承的Controller类全称，带包名</span></span><br><span class="line">        strategy.setControllerMappingHyphenStyle(<span class="keyword">true</span>);<span class="comment">// Controller中驼峰转连字符</span></span><br><span class="line">        strategy.setRestControllerStyle(<span class="keyword">true</span>); <span class="comment">//生成 @RestController 控制器</span></span><br><span class="line">        strategy.setTablePrefix(pc.getModuleName() + <span class="string">"_"</span>);<span class="comment">//表前缀</span></span><br><span class="line">        mpg.setStrategy(strategy);</span><br><span class="line">        <span class="comment">// 选择 freemarker 引擎需要指定如下加，注意 pom 依赖必须有！</span></span><br><span class="line">        mpg.setTemplateEngine(<span class="keyword">new</span> FreemarkerTemplateEngine());</span><br><span class="line">        mpg.execute();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="CRUD接口"><a href="#CRUD接口" class="headerlink" title="CRUD接口"></a>CRUD接口</h2><h3 id="Mapper-CRUD-接口"><a href="#Mapper-CRUD-接口" class="headerlink" title="Mapper CRUD 接口"></a>Mapper CRUD 接口</h3><p>说明:</p>
<ul>
<li>通用 CRUD 封装BaseMapper接口，为 Mybatis-Plus 启动时自动解析实体表关系映射转换为 Mybatis 内部对象注入容器</li>
<li>泛型 T 为任意实体对象</li>
<li>参数 Serializable 为任意类型主键 Mybatis-Plus 不推荐使用复合主键约定每一张表都有自己的唯一 id 主键</li>
<li>对象 Wrapper 为 条件构造器</li>
</ul>
<h3 id="Service-CRUD-接口"><a href="#Service-CRUD-接口" class="headerlink" title="Service CRUD 接口"></a>Service CRUD 接口</h3><p>说明:</p>
<ul>
<li>通用 Service CRUD 封装IService接口，进一步封装 CRUD 采用 get 查询单行 remove 删除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆，</li>
<li>泛型 T 为任意实体对象</li>
<li>建议如果存在自定义通用 Service 方法的可能，请创建自己的 IBaseService 继承 Mybatis-Plus 提供的基类</li>
<li>对象 Wrapper 为 条件构造器</li>
</ul>
<h3 id="条件构造器"><a href="#条件构造器" class="headerlink" title="条件构造器"></a>条件构造器</h3><p>示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Order&gt; <span class="title">orderPagingQueryStatus2</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    QueryWrapper&lt;Order&gt; queryWrapper = <span class="keyword">new</span> QueryWrapper&lt;&gt;();</span><br><span class="line">    queryWrapper.lambda().eq(Order::getStatus, <span class="number">0</span>).gt(Order::getCreatedAt,<span class="string">"2019-02-25 12:00:00"</span>);</span><br><span class="line">    <span class="keyword">return</span> list(queryWrapper);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="分页插件"><a href="#分页插件" class="headerlink" title="分页插件"></a>分页插件</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- spring xml 方式 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">plugins</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">plugin</span> <span class="attr">interceptor</span>=<span class="string">"com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"sqlParser"</span> <span class="attr">ref</span>=<span class="string">"自定义解析类、可以没有"</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"dialectClazz"</span> <span class="attr">value</span>=<span class="string">"自定义方言类、可以没有"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">plugin</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">plugins</span>&gt;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Spring boot方式</span></span><br><span class="line"><span class="meta">@EnableTransactionManagement</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@MapperScan</span>(<span class="string">"com.baomidou.cloud.service.*.mapper*"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MybatisPlusConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 分页插件</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> PaginationInterceptor <span class="title">paginationInterceptor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> PaginationInterceptor();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">Mapper.java</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 包含街区、租客多表查询(注解和xml同时存在的时候，跳过注解)</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> page 分页</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">List&lt;Order&gt; <span class="title">orderPagingQuery</span><span class="params">(Page page, @Param(<span class="string">"operateUserId"</span>)</span> Long operateUserId)</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Service.java</span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 订单分页查询</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> page</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">Page&lt;Order&gt; <span class="title">orderPagingQuery</span><span class="params">(Page&lt;Order&gt; page, Long operate_user_id)</span></span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">ServiceImpl.java</span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 订单分页查询</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> page</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Page&lt;Order&gt; <span class="title">orderPagingQuery</span><span class="params">(Page&lt;Order&gt; page, Long operateUserId)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> page.setRecords(<span class="keyword">this</span>.baseMapper.orderPagingQuery(page, operateUserId));</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">Controller.java</span><br><span class="line"> <span class="meta">@GetMapping</span>(value = <span class="string">"/orders"</span> )</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">orders</span><span class="params">(@RequestParam(value = <span class="string">"page"</span>, defaultValue = <span class="string">"1"</span>)</span> Integer pn,</span></span><br><span class="line"><span class="function">                         @<span class="title">RequestParam</span><span class="params">(value = <span class="string">"size"</span>, defaultValue = <span class="string">"10"</span>)</span> Integer pageSize, Principal principal) </span>&#123;</span><br><span class="line">        <span class="comment">//获取当前用户的订单,需要另外写</span></span><br><span class="line">        <span class="keyword">long</span> operate_user_id = userService.selectUserByMobile(principal.getName()).getId();</span><br><span class="line">        <span class="comment">//利用mybatis-plus的分页查询</span></span><br><span class="line">        Page&lt;Order&gt; obt = orderService.orderPagingQuery(<span class="keyword">new</span> Page&lt;&gt;(pn, pageSize), operate_user_id);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> RetResult(obt);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>同时可以自定义分页</p>
<h4 id="UserMapper-java"><a href="#UserMapper-java" class="headerlink" title="UserMapper.java"></a>UserMapper.java</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserMapper</span></span>&#123;<span class="comment">//可以继承或者不继承BaseMapper</span></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;</span></span><br><span class="line"><span class="comment">     * 查询 : 根据state状态查询用户列表，分页显示</span></span><br><span class="line"><span class="comment">     * 注意!!: 如果入参是有多个,需要加注解指定参数名才能在xml中取值</span></span><br><span class="line"><span class="comment">     * &lt;/p&gt;</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> page 分页对象,xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位(你可以继承Page实现自己的分页对象)</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> state 状态</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 分页对象</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">IPage&lt;User&gt; <span class="title">selectPageVo</span><span class="params">(Page page, @Param(<span class="string">"state"</span>)</span> Integer state)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="UserMapper-xml"><a href="#UserMapper-xml" class="headerlink" title="UserMapper.xml"></a>UserMapper.xml</h4><p>等同于编写一个普通 list 查询，mybatis-plus 自动替你分页</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"selectPageVo"</span> <span class="attr">resultType</span>=<span class="string">"com.baomidou.cloud.entity.UserVo"</span>&gt;</span></span><br><span class="line">    SELECT id,name FROM user WHERE state=#&#123;state&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="UserServiceImpl-java"><a href="#UserServiceImpl-java" class="headerlink" title="UserServiceImpl.java"></a>UserServiceImpl.java</h4><p>调用分页方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> IPage&lt;User&gt; <span class="title">selectUserPage</span><span class="params">(Page&lt;User&gt; page, Integer state)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 不进行 count sql 优化，解决 MP 无法自动优化 SQL 问题，这时候你需要自己查询 count 部分</span></span><br><span class="line">    <span class="comment">// page.setOptimizeCountSql(false);</span></span><br><span class="line">    <span class="comment">// 当 total 为非 0 时(默认为 0),分页插件不会进行 count 查询</span></span><br><span class="line">    <span class="comment">// 要点!! 分页返回的对象与传入的对象是同一个</span></span><br><span class="line">    <span class="keyword">return</span> userMapper.selectPageVo(page, state));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="小问题"><a href="#小问题" class="headerlink" title="小问题"></a>小问题</h3><p>① 使用条件构造器的orderByDesc()等排序功能时会有，idea会报警告，<strong>目前无法解决。</strong></p>

      
    </div>
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束 <i class="fa fa-paw"></i> 感谢您的阅读-------------</div>
    
</div>

      
    </div>
    <div>
      
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/mybatis-plusStart/">mybatis-plus入坑指南</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 Big Jelly 的个人博客">Big Jelly</a></p>
  <p><span>发布时间:</span>2019年03月02日 - 16:12</p>
  <p><span>最后更新:</span>2020年03月07日 - 11:47</p>
  <p><span>原始链接:</span><a href="/mybatis-plusStart/" title="mybatis-plus入坑指南">https://jelly54.github.io/mybatis-plusStart/</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://jelly54.github.io/mybatis-plusStart/" aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>

      
    </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="Big Jelly 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="Big Jelly 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/框架/" rel="tag"><i class="fa fa-tag"></i> 框架</a>
          
            <a href="/tags/mybatis/" rel="tag"><i class="fa fa-tag"></i> mybatis</a>
          
            <a href="/tags/plugin/" rel="tag"><i class="fa fa-tag"></i> plugin</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/alg-frequenceCode/" rel="next" title="高频算法题-zs">
                <i class="fa fa-chevron-left"></i> 高频算法题-zs
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/springb-enum-gender/" rel="prev" title="SpringBoot-使用枚举整合性别等">
                SpringBoot-使用枚举整合性别等 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
	<div id="gitalk-container"></div>

  

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 展示广告 -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-3331353808689126" data-ad-slot="4663393885" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="Big Jelly">
            
              <p class="site-author-name" itemprop="name">Big Jelly</p>
              <p class="site-description motion-element" itemprop="description">Nothing is easier than to deceive oneself</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">55</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">68</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a rel="external nofollow" href="https://github.com/jelly54" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a rel="external nofollow" href="mailto:jelly_54@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                外链小站
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://leetcode.com/" title="LeetCode" rel="external nofollow" target="_blank">LeetCode</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.dooccn.com/" title="在线编辑代码" rel="external nofollow" target="_blank">在线编辑代码</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.chuangzaoshi.com/code" title="创造狮导航" rel="external nofollow" target="_blank">创造狮导航</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://24mail.chacuo.net/?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=qq" title="24Mail" rel="external nofollow" target="_blank">24Mail</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://e.xitu.io/" title="掘金酱" rel="external nofollow" target="_blank">掘金酱</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#mybatis-plus入坑指南"><span class="nav-number">1.</span> <span class="nav-text">mybatis-plus入坑指南</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#简介"><span class="nav-number">1.1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#特性"><span class="nav-number">1.2.</span> <span class="nav-text">特性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#框架结构"><span class="nav-number">1.3.</span> <span class="nav-text">框架结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#好了官网的简介完了，附上github地址：Mybatis-plus的GIthub"><span class="nav-number">1.4.</span> <span class="nav-text">好了官网的简介完了，附上github地址：Mybatis-plus的GIthub</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#基本使用"><span class="nav-number">2.</span> <span class="nav-text">基本使用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#功能列表："><span class="nav-number">2.1.</span> <span class="nav-text">功能列表：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#安装"><span class="nav-number">2.2.</span> <span class="nav-text">安装</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#添加依赖"><span class="nav-number">2.2.1.</span> <span class="nav-text">添加依赖</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#添加包扫描"><span class="nav-number">2.2.2.</span> <span class="nav-text">添加包扫描</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#警告"><span class="nav-number">2.2.3.</span> <span class="nav-text">警告</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Mybatis-plus的配置"><span class="nav-number">3.</span> <span class="nav-text">Mybatis-plus的配置</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#在application-yml中添加数据源"><span class="nav-number">3.1.</span> <span class="nav-text">在application.yml中添加数据源</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#核心功能"><span class="nav-number">4.</span> <span class="nav-text">核心功能</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#代码生成器"><span class="nav-number">4.1.</span> <span class="nav-text">代码生成器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#CRUD接口"><span class="nav-number">4.2.</span> <span class="nav-text">CRUD接口</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Mapper-CRUD-接口"><span class="nav-number">4.2.1.</span> <span class="nav-text">Mapper CRUD 接口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Service-CRUD-接口"><span class="nav-number">4.2.2.</span> <span class="nav-text">Service CRUD 接口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#条件构造器"><span class="nav-number">4.2.3.</span> <span class="nav-text">条件构造器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#分页插件"><span class="nav-number">4.2.4.</span> <span class="nav-text">分页插件</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#UserMapper-java"><span class="nav-number">4.2.4.1.</span> <span class="nav-text">UserMapper.java</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#UserMapper-xml"><span class="nav-number">4.2.4.2.</span> <span class="nav-text">UserMapper.xml</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#UserServiceImpl-java"><span class="nav-number">4.2.4.3.</span> <span class="nav-text">UserServiceImpl.java</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#小问题"><span class="nav-number">4.2.5.</span> <span class="nav-text">小问题</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

      <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
      <!-- 侧边栏广告 -->
      <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-3331353808689126" data-ad-slot="7563237003" data-ad-format="auto" data-full-width-responsive="true"></ins>
      <script>
      	(adsbygoogle = window.adsbygoogle || []).push({});
      </script>
    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright"> &copy; 2017 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Big Jelly</span>

</div>

<div class="powered-by">
	
		<span class="post-meta-item-icon">
			<i class="fa fa-area-chart"></i>
		</span>
		
			<span class="post-meta-item-text">Site words total count&#58;</span>
		
		<span title="Site words total count">140.8k</span>
	
  
	
		<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

		<span class="post-meta-divider">|</span>
		<span class="post-visit-item-icon">
			<i class="fa fa-user-md"></i>
		</span>
		<span class="busuanzi_container_site_uv">
			Visitors to this site: <span id="busuanzi_value_site_uv"></span>
		</span>
	
  


	
</div>
        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
  <script src="/js/md5.min.js"></script>
   <script type="text/javascript">
        var gitalk = new Gitalk({
          clientID: 'ca31692554c3aea431f0',
          clientSecret: '1173c9e9c3c9038304c9a5b08929a359cae9f847',
          repo: 'jelly54.github.io',
          owner: 'jelly54',
          admin: ['jelly54'],
          id: md5(location.pathname),
          distractionFreeMode: 'true'
        })
        gitalk.render('gitalk-container')
       </script>

  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  



  
<script type="text/javascript" color="0,0,255" opacity="0.7" zindex="-2" count="99" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>


<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":true,"model":{"scale":1,"jsonPath":"/live2dw/assets/miku.model.json"},"display":{"position":"right","width":200,"height":400,"hOffset":0,"vOffset":-5},"mobile":{"show":true,"scale":0.5},"react":{"opacity":0.9},"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
